import router from "@/router/router";

import webSocketDict from "@/common/dict/dictCollections";
import $localStorage from "@/api/storage/localStorage";

let Socket = ''
let setIntervalWesocketPush = null
let webUrl = null
let userMessage = {
    "username": '',
    "code": 1
}
export const setUserMessage = (username, code = 1) => {
    userMessage.username = username
    userMessage.code = code
}
/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = url => {
    console.log("url====>", url)
    if (url != null) {
        webUrl = url
    }
    if (webUrl == null) {
        webUrl = $localStorage.get("websocketUrl")
        if (webUrl == null) {
            router.push({
                name: '/login',
                params: {
                    msg: "和服务器失去联系,请重新登录"
                }
            })
        }
        $localStorage.set("websocketUrl", url, 86400 * 1000)
    }
    if (!Socket) {
        Socket = new WebSocket(webUrl)
        Socket.onopen = onopenWS
        Socket.onmessage = onmessageWS
        Socket.onerror = onerrorWS
        Socket.onclose = oncloseWS
    } else {
        console.log('websocket已连接')
    }
}

/**打开WS之后发送心跳 */
const onopenWS = () => {
    sendPing()
}

function checkTokenIsExists() {
    Socket = null;
    let token = $localStorage.get("token");
    if (token == null) {
        router.push("/login")
    } else {
        createSocket(webUrl)
        router.push("/")
    }
}

/**连接失败重连 */
const onerrorWS = () => {
    Socket.close()
    clearInterval(setIntervalWesocketPush)
    if (Socket.readyState !== 3) {
        checkTokenIsExists();
    }
}

async function destroyData() {
    webUrl = null
    userMessage.code = 2
    await sendWSPush(userMessage)
    Socket.close();
}

async function toLogin(e) {
    let msg = webSocketDict[e.data].value
    await router.push({
        name: '/login',
        params: {
            msg: msg
        }
    })
}

/**WS数据接收统一处理 */
const onmessageWS = async e => {
    if (e.data == 2) {
        await destroyData()
        await toLogin(e);
    }
    if (e.data == 10002) {
        $localStorage.clear()
        await destroyData()
        await toLogin(e);
    }
    if (e.data == 999) {
        await destroyData();
        await toLogin(e);
    }
    if (e.data==888){
        await destroyData();
        await toLogin(e)
    }
}

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} userMessage 需要发送的数据
 */
const connecting = userMessage => {
    setTimeout(() => {
        if (Socket.readyState === 0) {
            connecting(userMessage)
        } else {
            Socket.send(JSON.stringify(userMessage))
        }
    }, 1000)
}

/**
 * 发送数据
 * @param {any} userMessage 需要发送的数据
 */
export const sendWSPush = userMessage => {
    if (Socket !== null && Socket.readyState === 3) {
        Socket.close()
        createSocket(webUrl)
    } else if (Socket.readyState === 1) {
        Socket.send(JSON.stringify(userMessage))
    } else if (Socket.readyState === 0) {
        connecting(userMessage)
    }
}

/**断开重连 */
const oncloseWS = () => {
    clearInterval(setIntervalWesocketPush)
    if (Socket.readyState !== 2) {
        checkTokenIsExists()
    }
}
/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 5000, ping = 'ping') => {
    clearInterval(setIntervalWesocketPush)
    Socket.send(JSON.stringify(userMessage))
    setIntervalWesocketPush = setInterval(() => {
        Socket.send(JSON.stringify(userMessage))
    }, time)
}
